<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { register } from '@/api/user'
import AuthBackground from '../components/AuthBackground.vue'

const router = useRouter()
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  agreement: false
})

const loading = ref(false)

const handleRegister = async () => {
  // 表单验证
  if (!form.username || !form.password || !form.confirmPassword) {
    ElMessage.warning('Please fill in all information')
    return
  }
  
  if (form.password !== form.confirmPassword) {
    ElMessage.warning('The passwords you entered do not match')
    return
  }
  
  if (!form.agreement) {
    ElMessage.warning('Please agree to the service terms')
    return
  }
  
  loading.value = true
  try {
    await register({
      username: form.username,
      password: form.password,
      confirmPassword: form.confirmPassword
    })
    
    ElMessage.success('Registration successful')
    router.push('/login')
  } catch (error) {
    console.error('Registration failed:', error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <AuthBackground>
    <h2 class="title">Register</h2>
    <el-form :model="form" label-position="top">
      <el-form-item label="Username">
        <el-input 
          v-model="form.username" 
          placeholder="Please enter your username"
          :disabled="loading" />
      </el-form-item>
      
      <el-form-item label="Password">
        <el-input 
          v-model="form.password" 
          type="password" 
          placeholder="Please enter your password"
          :disabled="loading" />
      </el-form-item>
      
      <el-form-item label="Confirm Password">
        <el-input 
          v-model="form.confirmPassword" 
          type="password" 
          placeholder="Please confirm your password"
          :disabled="loading" />
      </el-form-item>
      
      <el-form-item>
        <el-checkbox 
          v-model="form.agreement"
          :disabled="loading">
          I accept the service regulations
        </el-checkbox>
      </el-form-item>
      
      <el-form-item>
        <el-button 
          type="primary" 
          @click="handleRegister" 
          style="width: 100%"
          :loading="loading">
          Register
        </el-button>
      </el-form-item>
    </el-form>
    
    <div class="login-link">
      Already have an account? 
      <router-link to="/login">Login</router-link>
    </div>
  </AuthBackground>
</template>

<style scoped>
.title {
  text-align: center;
  color: #1890ff;
  margin-bottom: 2rem;
}

.login-link {
  text-align: center;
  margin-top: 1rem;
  color: #666;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style> 